package valoskmdev.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import valoskmdev.bean.AppUser;
import valoskmdev.util.Utils;

import com.google.appengine.api.users.User;
import com.servlet.PMF;

public class UserDao {

	private UserDao() {
	}

	public static final int ENTITIES_PER_PAGE = 100;

	public static AppUser insertNew(final PersistenceManager pm, AppUser appUser) {

		pm.makePersistent(appUser);
		return appUser;
	}

	@SuppressWarnings("unchecked")
	public static List<AppUser> getUsers(final PersistenceManager pm, final int indexOffset,
			final String wordToSearch) {

		final Query query = pm.newQuery(AppUser.class);
		if (!Utils.isEmptyOrNull(wordToSearch)) {
			query.setFilter("lastName == lastNameParam");
		}
		query.declareParameters("String lastNameParam");
		query.setRange(indexOffset, indexOffset + ENTITIES_PER_PAGE + 1);
		query.setOrdering("timeCreated desc");
		final List<AppUser> appUsers = new ArrayList<AppUser>((List<AppUser>) query.execute(wordToSearch));

		return appUsers;

	}

	public static AppUser getUser(final PersistenceManager pm, final Long id) {

		final Query query = pm.newQuery(AppUser.class, "id == idParam");
		query.declareParameters("String idParam");
		query.setUnique(true);
		return (AppUser) query.execute(id);

	}
	
	public static AppUser getUser(final PersistenceManager pm, final User user) {

		final Query query = pm.newQuery(AppUser.class, "user == userParam");
		query.declareParameters("com.google.appengine.api.users.User userParam");
		query.setUnique(true);
		return (AppUser) query.execute(user);

	}


	public static void updateUser(final String userId, final String firstName, final String lastName, final String role,
			final String userName, final Date timeExpire) {

		PersistenceManager pmUpdate = null;
		try {
			pmUpdate = PMF.get().getPersistenceManager();
			final AppUser appUser = pmUpdate.getObjectById(AppUser.class, Long.valueOf(userId));
			appUser.setFirstName(firstName);
			appUser.setLastName(lastName);
			appUser.setTimeLastModified(new Date());
			appUser.setRoleName(role);
			appUser.setUserName(userName);
		} finally {
			if (pmUpdate != null) {
				pmUpdate.close();
			}
		}
	}

}
